/*
 *
 * This is a VoIP Application designed for local-network usage for voice and
 * messaging
 * Copyright (C) 2012  Imran M Yousuf (imyousuf@smitsol.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.smitsol.voip.server;

import com.smitsol.voip.api.Binding;
import com.smitsol.voip.server.sip.SipUtils;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.TooManyHopsException;

/**
 *
 * @author imyousuf
 */
public class SmartVoIPProxyServlet extends AbstractSmartVoIPSipServlet {

  @Override
  protected void doInvite(SipServletRequest ssr) throws ServletException, IOException {
    logger.info("Received INVITE to " + ssr.getRequestURI().toString() + " for " + ssr.getTo().getURI().toString() +
        " from " + ssr.getFrom().toString());
    proxyMessage(ssr);
  }

  private boolean proxyMessage(SipServletRequest ssr) throws IOException, TooManyHopsException, ServletParseException {
    String canonicalToUser = SipUtils.getCanonicalUri(ssr.getTo().getURI());
    List<Binding> bindings = getAPI().getBindingService().getBindings(canonicalToUser);
    if (bindings == null || bindings.isEmpty()) {
      ssr.createResponse(SipServletResponse.SC_NOT_FOUND).send();
      return false;
    }
    for (Binding binding : bindings) {
      ssr.getProxy().proxyTo(getSipFactory().createURI(binding.getContactHeader()));
    }
    return true;
  }

  @Override
  protected void doMessage(SipServletRequest ssr) throws ServletException, IOException {
    logger.info("Received MESSAGE to " + ssr.getRequestURI().toString() + " for " + ssr.getTo().getURI().toString() +
        " from " + ssr.getFrom().toString());
    proxyMessage(ssr);

  }
}
